package com.business.web.spring;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//import com.workflow.WorkFlowUtils;
import com.common.db.JsonVO;
import com.common.db.Pg;
import com.common.utils.BeanUtils;
import com.common.utils.MyDateUtils;
import com.auth.domain.T_function;
import com.business.domain.T_product;
//import com.business.mapper.T_productMapper;
import com.business.service.T_productService;

@Controller
@RequestMapping("/t_product")

public class T_productController
{
	private static Logger log = Logger.getLogger(T_productController.class.getName());

	@Resource
    private T_productService t_productService;

	//@Autowired
	//private WorkFlowUtils workFlowUtils;

	//@Resource
	//private T_productMapper mapper;
	//private int id;
	//private int[] ids;
	private Pg pg;

	/**
	 * 1.1、获取 T_product信息列表，并且在列表页面展示
	 * @param request
	 * @return Pg，json格式
	 */
	@RequestMapping("/getAllT_product")
	@ResponseBody
	public Pg findAll(HttpServletRequest request){
        int pageSize = 10;
        int startIndex = 0;
        T_product t_product = new T_product();
        try{
	        if(request.getParameter("pageSize")!=null){
	        	pageSize = BeanUtils.stringToInt("pageSizeFlag", request.getParameter("pageSize"));
	        }
	        if(request.getParameter("startIndex")!=null){
	            startIndex = BeanUtils.stringToInt("startIndexFlag", request.getParameter("startIndex"));
	        }
	        if(request.getParameter("process_code")!=null){ //取得动作流 流程英文名称，后台查询数据关联使用
	        	t_product.setProcess_code(request.getParameter("process_code"));
	        }
			if(request.getParameter("pname")!=null&&!"".equals(request.getParameter("pname"))){
	        	t_product.setPname(request.getParameter("pname"));
	        }
			if(request.getParameter("pmemo")!=null&&!"".equals(request.getParameter("pmemo"))){
	        	t_product.setPmemo(request.getParameter("pmemo"));
	        }
			if(request.getParameter("level")!=null&&!"".equals(request.getParameter("level"))){
	        	t_product.setLevel(request.getParameter("level"));
	        }
			if(request.getParameter("status")!=null&&!"".equals(request.getParameter("status"))){
	        	t_product.setStatus(request.getParameter("status"));
	        }
			if(request.getParameter("ext1")!=null&&!"".equals(request.getParameter("ext1"))){
	        	t_product.setExt1(request.getParameter("ext1"));
	        }
			if(request.getParameter("ext2")!=null&&!"".equals(request.getParameter("ext2"))){
	        	t_product.setExt2(request.getParameter("ext2"));
	        }
			if(request.getParameter("ext3")!=null&&!"".equals(request.getParameter("ext3"))){
	        	t_product.setExt3(request.getParameter("ext3"));
	        }
			if(request.getParameter("inserttime")!=null&&!"".equals(request.getParameter("inserttime"))){
	        	t_product.setInserttime(request.getParameter("inserttime"));
	        }
			if(request.getParameter("updatetime")!=null&&!"".equals(request.getParameter("updatetime"))){
	        	t_product.setUpdatetime(request.getParameter("updatetime"));
	        }
			if(request.getParameter("creater")!=null&&!"".equals(request.getParameter("creater"))){
	        	t_product.setCreater(request.getParameter("creater"));
	        }
			if(request.getParameter("updater")!=null&&!"".equals(request.getParameter("updater"))){
	        	t_product.setUpdater(request.getParameter("updater"));
	        }
      	    if(request.getParameter("product_id")!=null&&!"".equals(request.getParameter("product_id"))){
	        	t_product.setProduct_id(new Integer(request.getParameter("product_id")));
	        }
      	    if(request.getParameter("pid")!=null&&!"".equals(request.getParameter("pid"))){
	        	t_product.setPid(new Integer(request.getParameter("pid")));
	        }
	        if(request.getParameter("startdate")!=null&&!"".equals(request.getParameter("startdate"))){
	        	t_product.setStartdate(request.getParameter("startdate"));
	        }
	        if(request.getParameter("enddate")!=null&&!"".equals(request.getParameter("enddate"))){
	        	t_product.setEnddate(request.getParameter("enddate"));
	        }
	        t_product.setStartNo( startIndex );
	        t_product.setPageSize( pageSize );
	        t_product.setEndNo( pageSize );
	    	List<T_product> findAll = sortProductList (t_productService.findAll(t_product)); //进行树形排列

	        int totalCount = t_productService.findCountAll(t_product);
	       	pg = new Pg(findAll, totalCount, pageSize, startIndex);
	       	request.setAttribute("t_productList", findAll);
		    request.setAttribute("pg", pg);
	    } catch (Exception e) {
			e.printStackTrace();
			log.error("------query t_productList error:"+e);
		}

		return pg;
	}

	/**
	 * 1.2、获取 T_product信息列表，并且在列表页面展示
	 * @param request
	 * @return Pg，json格式
	 */
	@RequestMapping("/getAllT_productByPid")
	@ResponseBody
	public Pg getAllT_productByPid(HttpServletRequest request){
        int pageSize = 10;
        int startIndex = 0;
        T_product t_product = new T_product();
        try{
	        if(request.getParameter("pageSize")!=null){
	        	pageSize = BeanUtils.stringToInt("pageSizeFlag", request.getParameter("pageSize"));
	        }
	        if(request.getParameter("startIndex")!=null){
	            startIndex = BeanUtils.stringToInt("startIndexFlag", request.getParameter("startIndex"));
	        }
	        if(request.getParameter("process_code")!=null){ //取得动作流 流程英文名称，后台查询数据关联使用
	        	t_product.setProcess_code(request.getParameter("process_code"));
	        }
			if(request.getParameter("pname")!=null&&!"".equals(request.getParameter("pname"))){
	        	t_product.setPname(request.getParameter("pname"));
	        }
			if(request.getParameter("pmemo")!=null&&!"".equals(request.getParameter("pmemo"))){
	        	t_product.setPmemo(request.getParameter("pmemo"));
	        }
			if(request.getParameter("level")!=null&&!"".equals(request.getParameter("level"))){
	        	t_product.setLevel(request.getParameter("level"));
	        }
			if(request.getParameter("status")!=null&&!"".equals(request.getParameter("status"))){
	        	t_product.setStatus(request.getParameter("status"));
	        }
			if(request.getParameter("ext1")!=null&&!"".equals(request.getParameter("ext1"))){
	        	t_product.setExt1(request.getParameter("ext1"));
	        }
			if(request.getParameter("ext2")!=null&&!"".equals(request.getParameter("ext2"))){
	        	t_product.setExt2(request.getParameter("ext2"));
	        }
			if(request.getParameter("ext3")!=null&&!"".equals(request.getParameter("ext3"))){
	        	t_product.setExt3(request.getParameter("ext3"));
	        }
			if(request.getParameter("inserttime")!=null&&!"".equals(request.getParameter("inserttime"))){
	        	t_product.setInserttime(request.getParameter("inserttime"));
	        }
			if(request.getParameter("updatetime")!=null&&!"".equals(request.getParameter("updatetime"))){
	        	t_product.setUpdatetime(request.getParameter("updatetime"));
	        }
			if(request.getParameter("creater")!=null&&!"".equals(request.getParameter("creater"))){
	        	t_product.setCreater(request.getParameter("creater"));
	        }
			if(request.getParameter("updater")!=null&&!"".equals(request.getParameter("updater"))){
	        	t_product.setUpdater(request.getParameter("updater"));
	        }
      	    if(request.getParameter("product_id")!=null&&!"".equals(request.getParameter("product_id"))){
	        	t_product.setProduct_id(new Integer(request.getParameter("product_id")));
	        }
      	    if(request.getParameter("pid")!=null&&!"".equals(request.getParameter("pid"))){
	        	t_product.setPid(new Integer(request.getParameter("pid")));
	        }
	        if(request.getParameter("startdate")!=null&&!"".equals(request.getParameter("startdate"))){
	        	t_product.setStartdate(request.getParameter("startdate"));
	        }
	        if(request.getParameter("enddate")!=null&&!"".equals(request.getParameter("enddate"))){
	        	t_product.setEnddate(request.getParameter("enddate"));
	        }
	        t_product.setStartNo( startIndex );
	        t_product.setPageSize( pageSize );
	        t_product.setEndNo( pageSize );
	    	List<T_product> findAll = t_productService.findAll(t_product); //不能进行树形排列，否则前端jsp无法显示；层级有问题

	        int totalCount = t_productService.findCountAll(t_product);
	       	pg = new Pg(findAll, totalCount, pageSize, startIndex);
	       	request.setAttribute("t_productList", findAll);
		    request.setAttribute("pg", pg);
	    } catch (Exception e) {
			e.printStackTrace();
			log.error("------query t_productList error:"+e);
		}

		return pg;
	}

	/**
	 * 2、新增保存  T_product信息并且返回成功或者失败信息json格式结果如：result:[success/error]
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveT_product")
	@ResponseBody
	public JsonVO saveT_product(T_product t_product, HttpServletRequest request,HttpServletResponse response){
		JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);
		//设置当前操作用户信息到vo中
		t_product.setCreater(request.getSession().getAttribute("FREE_CURRENT_USER")+"");
		t_product.setInserttime(MyDateUtils.getDate());
		t_product.setUpdater(request.getSession().getAttribute("FREE_CURRENT_USER")+"");
		//取得上级菜单对应的信息，把级别+1，设置到级别字段属性中，为新增菜单设置默认菜单级别值；
		t_product.setLevel(getProductLevel(t_product.getPid()));

		//如果有特殊需求，需要将json对象值转成java实体对象属性值
		if(t_productService.save(t_product)>0){
	        vo.setResult("success");
	        vo.setJieguo(true);
		}
		return vo;
	}

	/**
	 * 根据上级菜单level，加工当前菜单level；初始化数据中，总公司的菜单级别为0；
	 * @param parentFunctionId
	 * @return
	 */
	private String getProductLevel(int pid){
		//取得上级机构对应的信息，把机构级别+1，设置到机构级别字段属性中，为新增机构设置默认机构级别值；
		T_product obj = new T_product();
		obj.setProduct_id(pid);
		obj = t_productService.findById(obj);
		int bl = new Integer(obj.getLevel())+1;
		return bl+"";
	}

	/**
	 * 3、修改T_product信息并且返回成功或者失败信息json格式结果如：result:[success/error]
	 * @param t_product
	 * @param request
	 * @return JsonVO
	 */
	@RequestMapping("/updateT_product")
	@ResponseBody
	public JsonVO updateT_product(T_product t_product, HttpServletRequest request){
		JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);
		//如果有特殊值需要处理，在此处手工转换
		//T_product t_productTemp = t_productService.findById(t_product);
		//t_productTemp.setXXX(t_product.getXXX());
		//if(t_productService.update(t_productTemp)){

		//取得上级菜单对应的信息，把级别+1，设置到级别字段属性中，为新增菜单设置默认菜单级别值；
		t_product.setLevel(getProductLevel(t_product.getPid()));

		if(t_productService.update(t_product)>0){
	        vo.setResult("success");
	        vo.setJieguo(true);
		}
		return vo;
	}

	/**
	 * 4、根据id查询T_product单个信息并显示在修改页面
	 * @param id
	 * @param request
	 * @return T_product json格式字符串
	 */
	@RequestMapping("/getT_product")
	@ResponseBody
	public T_product getT_product(Integer id,HttpServletRequest request){
		T_product t_product = new T_product();
		t_product.setProduct_id(id);
		return t_productService.findById(t_product);
	}

	/**
	 * 5、删除T_product根据id
	 * @param id
	 * @param request
	 * @param response
	 * return JsonVO ：json格式字符串
	 */
	@RequestMapping("/delT_product")
	@ResponseBody
	public JsonVO delT_product(Integer id,HttpServletRequest request,HttpServletResponse response){
        JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);

		T_product t_product = new T_product();
		t_product.setProduct_id(id);

		if(t_productService.delete(t_product)>0){
			vo.setResult("success");
	        vo.setJieguo(true);
		}
		return vo;
	}

	/**
	 * 6、跳转到t_product/toT_productList查询所有数据页面
	 *  return /WEB-INF/views/business/t_product/t_productList.jsp
	 */
    @RequestMapping(value = "/toT_productList")
    public String toT_productList() {
    	log.debug("------跳转到/WEB-INF/views/business/t_product/t_productList.jsp------");
        return "business/t_product/t_productList";
    }

	/**
	 * 7、新增、修改、详情页面t_product/toT_productCurd跳转
     * business/t_product/T_productCurd.jsp
	 */
    @RequestMapping(value = "/toT_productCurd")
    public String toT_productCurd() {
    	log.debug("------跳转到/WEB-INF/views/business/t_product/t_productCurd.jsp------");
        return "business/t_product/t_productCurd";
    }

    /**
	 * 8、批量删除T_product根据主键id
	 * 是否要实现批量删除，待考虑，基本上用途不大
	 * @param id
	 * @param request
	 * @param response
	@RequestMapping("/delT_productBatch")
	public String delT_productBatch(HttpServletRequest request,HttpServletResponse response){
		String[] ids = request.getParameterValues("ids");
		System.out.println("------ids="+ids);
		T_product t_product = new T_product();
		int j=0;
		for(int i =0;i< ids.length;i++){
			j++;
			log.error("------ids[i]="+ids[i]);
			t_product.setProduct_id(new Integer(ids[i]).intValue());
			t_productService.delete(t_product);
		}
		if(j==ids.length){
			log.debug("------t_product批量删除成功！------");
		}else{
			log.error("------t_product批量删除部分成功！部分失败！------");
		}

		return "redirect:/t_product/getAllT_product";
	}
*/

	/**
	 * 对product进行sort排序，按照showseq，分级排序；显示成一棵树，
	 * 前提条件是，inlist的数据要首先sql中执行： order by level,  showseq;然后再用此方法就可以排列成一棵树
	 * @param inlist
	 * @return
	 */
	public static List sortProductList(List inlist){
		//Collections.sort(inlist);
		T_product one, two, three;

		List mubiaoList = new ArrayList();
		List oneLevel = new ArrayList();
		List twoLevel = new ArrayList();
		List threeLevelList = new ArrayList();

		Iterator it, it2, it3, it4, it5;

		it = inlist.iterator();
		while(it.hasNext()){
			one = (T_product)it.next();
			if(one.getLevel().equals("0")||one.getPid()==null){
				mubiaoList.add(one);
				log.debug("******0Leveladd="+one.getPname()+";productid="+one.getProduct_id());

			}else if(one.getLevel().equals("1")){
				mubiaoList.add(one);
				log.debug("------1Leveladd="+one.getPname()+";productid="+one.getProduct_id());

				it2 = inlist.iterator();
				while(it2.hasNext()){
					two = (T_product)it2.next();
					//注意：one.getProduct_id()为Integer类型，是对象，判断是否相等要用equals方法，用==会出现false的情况；
					//log.debug("------------2Level "+two.getPname()+";"+one.getProduct_id()+";"+two.getPid()+"?是否相等="+(two.getPid()==one.getProduct_id()));
					//log.debug("------------2Level，当前元素是否需要计入:two.getPid()="+two.getPid()+";one.getProduct_id()="+one.getProduct_id()+";是否相等="+(two.getPid()==one.getProduct_id()));

					if(two.getPid()!=null&&two.getPid().equals(one.getProduct_id())){
						mubiaoList.add(two);
						log.debug("------------2Level.add="+two.getPname()+";functid="+two.getProduct_id());

						it3 = inlist.iterator();
						while(it3.hasNext()){
							three = (T_product)it3.next();
							if(three.getPid()!=null&&three.getPid().equals(two.getProduct_id())){
								mubiaoList.add(three);
								log.debug("------------------3Level.add="+three.getPname()+";functid="+three.getProduct_id());


							}
						}
					}
				}
				log.debug("------1Level循环结束------------------"+one.getPname());
			}
		}
		return mubiaoList;
	}


}









